<template>
	<div>
		<template v-show="status !== 'hidden'" v-if="notEmpty(infoData)">
			<div class="contentor">
				<div class="info">
					<div class="search">
						<span class="tag"></span>
						<div class="info_title">
							{{ title }}
						</div>
						<div class="total">
							共计{{ totalListLength }}个报销明细，合计{{
								format_thousand(totalPrice)
							}}元
						</div>
						<div>
							<el-button
								v-show="status !== 'readonly'"
								:disabled="status !== 'write'"
								type="primary"
								icon="el-icon-upload2"
								@click="verification_open"
								size="mini">
								导入
							</el-button>
						</div>
					</div>
				</div>
				<div class="orderList">
					<el-form
						ref="form"
						:model="infoData"
						label-width="5px"
						inline
						:hide-required-asterisk="true">
						<el-table
							:data="infoData.businessInfoVos"
							style="width: 100%"
							border
							:header-cell-class-name="setHeaderCellName">
							<el-table-column
								label="操作"
								align="center"
								fixed="right"
								v-if="status == 'write'">
								<template slot-scope="scope">
									<el-button type="text" @click="deleteRow(scope.$index)">
										删除
									</el-button>
								</template>
							</el-table-column>
							<TableCloumn
								v-for="item in tableClounms"
								:cellOptions="item"
								:state="state"
								dataName="businessInfoVos"
								min-width="150px"></TableCloumn>
						</el-table>
					</el-form>
					<div @click="pushTableData" class="btn" v-if="status === 'write'">
						<i class="el-icon-plus"></i>
						增加一行
					</div>
				</div>
				<div>
					<FormItems
						ref="form1"
						v-model="infoData"
						:form="formList"
						:state="state"></FormItems>
				</div>
			</div>
		</template>
		<el-dialog
			:visible.sync="dialog.verification.show"
			width="600px"
			:show-close="false"
			@closed="verification_init">
			<template #title>
				<div class="dialog_title">
					<div class="main">付款流水核销</div>
				</div>
			</template>
			<div class="uploadFileBox">
				<el-upload
					class="upload-demo"
					ref="upload_ui"
					action="#"
					:file-list="filelist"
					:http-request="uploadFile"
					:limit="1"
					:auto-upload="false"
					accept=".xlsx">
					<el-button slot="trigger" size="small" type="primary">选取文件</el-button>

					<div slot="tip" class="el-upload__tip">
						只能上传xlsx/xls文件，且不超过500kb
						<el-button type="text" size="default" @click="download_template">
							下载模板
						</el-button>
					</div>
				</el-upload>
			</div>
			<span slot="footer">
				<el-button
					@click="dialog.verification.show = false"
					:disabled="dialog.verification.state == 'uploading'">
					关闭
				</el-button>
				<el-button
					v-if="dialog.verification.state !== 'afterUpload'"
					:disabled="dialog.verification.state == 'uploading'"
					type="primary"
					@click="verification_sure">
					上传
				</el-button>
			</span>
		</el-dialog>
	</div>
</template>

<script>
	import TableCloumn from '@/views/finance/manage/tableColumn/index.vue';
	import { getToken } from '@/utils/auth';
	import Uploadui from '@/components/FileUpload/upload_ui.vue';
	import Upload from '@/components/FileUpload/pictureCard.vue';
	import PictureCard from '@/components/FileUpload/pictureCard.vue';
	import FormItems from '@/views/finance/manage/formItems/index.vue';
	import * as apis from '@/api/finance/reimburs/add/api.js';
	import * as app from '@/api/app.js';
	export default {
		inheritAttrs: true,
		components: { PictureCard, Upload, Uploadui, TableCloumn, FormItems },
		props: {
			value: {
				type: Object,
				required: true,
			},
			tableClounmOptions: {
				type: Array,
				required: true,
			},
			status: {
				default: 'write',
			},
			dictType: {
				default: '',
			},
			title: {
				default: '',
			},
			formData: {
				default: {},
			},
			state: {
				required: false,
			},
			type: {
				required: false,
			},
			applyType: {
				required: false,
			},
		},
		data() {
			return {
				input: '',
				options: [],
				newTableListData: {},
				file: {
					value1Images: [],
					value2Images: [],
				},
				priceDict: [],
				dialog: {
					verification: {
						show: false,
						queryParams: {
							url: '',
						},
						state: 'upload',
					},
				},
				filelist: [],
				baseUrl: process.env.VUE_APP_BASE_API,
				uploadFileUrl: process.env.VUE_APP_BASE_API + '/system/oss/upload', // 上传文件服务器地址
				headers: {
					Authorization: 'Bearer ' + getToken(),
				},
			};
		},
		filters: {},
		computed: {
			infoData: {
				get() {
					return this.value;
					// return this.useVModel.call(this);
				},
				set(value) {
					this.$emit('input', value);
				},
			},
			tableClounms: {
				get() {
					return this.tableClounmOptions;
				},
			},
			templateFileUrl() {
				return `${app.templateUrl}expense_${this.infoData.businessType}`;
			},
			totalListLength() {
				return this?.infoData?.businessInfoVos?.length ?? 0;
			},
			totalPrice() {
				let price = 0;

				price = this.infoData.businessInfoVos?.reduce((prev, next) => {
					if (
						Number.isFinite(Number(next.money))
						// && next.payFlag == '1'  假如是否需要支付为否需要不计算总额，打开注释
					) {
						return this.numberAdd(
							prev,
							this.notEmpty(next.money) ? next.money : next.monthMoney,
						);
					}
					return prev;
				}, price);

				return price ?? 0;
			},
			formList() {
				return [
					{
						label: '其他附件',
						prop: 'otherOssId',
						type: 'upload',
						block: true,
						fitContent: true,
						prototype: {
							upType: 2,
						},
						state: this.type === 'audit' ? 'readonly' : 'write',
					},
				];
			},
		},

		mounted() {},
		methods: {
			download_template() {
				this.downloadTemplate(
					`expense_${this.infoData.businessType}`,
					`报销信息导入模板_${new Date().getTime()}.xlsx`,
				);
			},
			uploadFile(item) {
				this.verification_state('afterUpload');

				// const formData = new FormData();
				// formData.append("file", item.file);
				// formData.append("id", this.uploadDialog.data.id);
				// formData.append("token", localStorage.getItem("token"));
				// PDFupload(formData).then((res) => {
				//
				// });
			},
			deleteRow(index) {
				this.infoData.businessInfoVos.splice(index, 1);
			},
			// 上传
			verification_open() {
				this.$UploadDialog({
					showtoastSureBtn: false,
					showResult: false,
					showErrorFeedback: false,
					uploadConfig: {
						uploadFileUrl: `#${apis?.ImportFile}`,
						limit: 1,
						params: {
							businessType: this.infoData.businessType,
						},
						fileType: ['xlsx'],
						templateUrl: this.templateFileUrl,
						templateName: `费用报销-${this.title}-导入模版.xlsx`,
					},
				}).then(res => {
					if (this.notEmpty(res)) {
						res?.map(item => {
							item.companyName ??= this?.formData?.companyName;
							item.companyId ??= this?.formData?.companyId;
							if (this.infoData.businessType == '3') {
								if (item?.startTime && item?.endTime) {
									let duration = this.getDateDuration(
										item.startTime,
										item.endTime,
									);
									item.stopTime = duration;
								}
							}
						});

						this.infoData.businessInfoVos.push(...res);
					}
				});
			},
			getDictValue(label, dict) {
				let item = dict.find(e => e.label?.toString() == label?.toString());
				if (item) {
					return item.value;
				}
			},
			getDateDuration(startTime, endTime) {
				let result = '-';
				let start = this.$dayjs(startTime);
				let end = this.$dayjs(endTime);
				let duration = this.$dayjs.duration(end.diff(start));
				let H_all = duration.as('hours');
				let D = parseInt(H_all / 24);
				let H = (H_all % 24).toFixed(1)?.split('.');
				if (D == 0) {
					result = `${H} 小时`;
				} else if ((H?.[0] == 0 && H?.[1] == 0) || (!H[0] && !H[1])) {
					result = `${D} 天`;
				} else if (H?.[1] == 0) {
					result = `${D} 天 ${H[0]} 小时`;
				} else {
					result = `${D} 天 ${H[0]}.${H[1]} 小时`;
				}
				return result;
			},
			verification_sure() {
				this.verification_state('uploading');
				this.$refs.upload_ui.submit();
			},
			// dialog关闭后触发
			verification_closed() {
				this.verification_init();
			},
			// 初始化数据
			verification_init() {
				this.dialog.verification.queryParams.url = '';
				this.verification_state('upload');
			},
			// 所有文件上传完毕后触发
			afterUpload() {
				this.verification_state('afterUpload');
			},
			uploadSuccess(res) {
				this.verification_closed();
			},
			// 修改上传状态，影响上传关闭按钮
			verification_state(state) {
				this.dialog.verification.state = state;
			},
			///////////////////////////////////////////

			valid() {
				return new Promise(async resolve => {
					let result = true;
					let refs = Object.values(this.$refs);
					for (let index = 0; index < refs?.length; index++) {
						const ref = refs[index];
						if (Object.prototype.toString.call(ref) == '[object Array]') {
							for (let i = 0; i < ref.length; i++) {
								const element = ref[i];
								if (element?.valid) {
									let rc = await element?.valid?.();
									result = result && rc;
								}
								if (element?.validate) {
									let rf = await this._valid(ref);
									result = result && rf;
								}
								if (element?.form_validate) {
									let rf = await this._valid(ref, 'form_validate');
									result = result && rf;
								}
							}
						} else {
							if (ref?.valid) {
								let rc = await ref?.valid?.();
								result = result && rc;
							}
							if (ref?.validate) {
								let rf = await this._valid(ref);
								result = result && rf;
							}
							if (ref?.form_validate) {
								let rf = await this._valid(ref, 'form_validate');
								result = result && rf;
							}
						}
					}

					resolve(result);
				});
			},
			pushTableData() {
				if (!('businessInfoVos' in this.infoData)) {
					this.$set(this.infoData, 'businessInfoVos', []);
					// this.infoData.list ??= [];
				}
				this.infoData.businessInfoVos.push({
					// companyName: this?.formData?.companyName,
					// companyId: this?.formData?.companyId,
					costType: '',
				});
			},
			select_dialog(item) {
				this.$refs.selectDialogInput?.[0]?.blur();
				if ('selectDialogValidate' in item) {
					if (!item.selectDialogValidate()) return;
				}
				this.$SelectDialog(item.selectDialogParams).then();
			},
			setHeaderCellName({ row, column, rowIndex, columnIndex }) {
				let whiteNames = [
					'所属公司',
					'车牌',
					'车架号',
					'新车/旧车',
					'车型',
					'车辆类型',
					'登记类型',
					'客户',
					'备注1',
					'备注2',
					'备注3',
					'操作',
					'办理事项（详细）',
				];
				let itemConfig = this.tableClounms?.find(e => e.label === column.label);

				if (
					!whiteNames.includes(column.label) &&
					'type' in itemConfig &&
					itemConfig.type !== 'text' &&
					'rules' in itemConfig
				) {
					return 'ruleHeaderCell';
				} else {
					return '';
				}
			},
		},
	};
</script>

<style scoped lang="scss">
	.contentor {
		// background-color: #fff;
		background-color: #f7fbff;
		font-size: 14px;
		border-radius: 4px;
		padding: 15px;
		.info {
			display: flex;
			justify-content: space-between;
			align-items: center;
			.search {
				width: 100%;
				display: flex;
				align-items: center;
				padding: 0 0 15px 0;
				> div {
					display: flex;
					align-items: center;
					margin-right: 10px;
				}
				::v-deep .el-radio-group {
					margin-top: 3px;
				}
				.tag {
					width: 8px;
					height: 8px;
					background-color: #1890ff;
					border-radius: 100%;
					margin-right: 10px;
				}
				.info_title {
					font-family: PingFangSC, PingFang SC;
					font-weight: 500;
					font-size: 14px;
					color: #333333;
					line-height: 20px;
					text-align: left;
					font-style: normal;
				}
				.total {
					font-family: PingFangSC, PingFang SC;
					font-weight: 400;
					font-size: 14px;
					color: #1890ff;
					line-height: 20px;
					text-align: left;
					font-style: normal;
					padding-left: 20px;
				}
			}
		}
		.btn {
			display: flex;
			justify-content: center;
			align-items: center;
			height: 48px;
			background: #ffffff;
			border-radius: 4px;
			border: 1px solid #dadada;
			color: #1890ff;
			margin-top: 15px;
			font-size: 14px;
			cursor: pointer;
		}
		.invoice {
			margin-top: 25px;
			padding: 25px;
			display: grid;
			grid-template-columns: minmax(0, 1fr) minmax(0, 1fr);
			gap: 15px 50px;
			.item {
				display: flex;
				align-items: center;
				.label {
					width: 100px;
					text-align: right;
					padding-right: 20px;
					// align-self: flex-start;
				}
				::v-deep .content {
					flex: 1;
					display: flex;
					flex-direction: row;
					flex-wrap: wrap;
					--w: 300px;
					.el-select {
						width: 100%;
						max-width: var(--w);
					}
					.el-input {
						width: 100%;
						max-width: var(--w);
					}
				}
			}
			.flexStart {
				align-items: flex-start;
				align-self: flex-start;
				.label {
					line-height: 100px;
				}
				.content {
					display: flex;
					gap: 15px;
					flex-wrap: wrap;
					min-height: 135px;
				}
			}
		}
	}
	::v-deep .el-form-item {
		margin-right: 0;
		display: flex;
		padding-right: 5px;
		box-sizing: border-box;
		// .el-form-item__content {
		//     margin-left: 0 !important;
		// }
		.el-form-item__label {
			word-break: keep-all;
		}
		.el-form-item__content {
			height: auto !important;
			flex: 1;
			// display: flex;
			// justify-content: center;
		}
	}
	.flexCenter {
		display: flex;
		justify-content: center;
	}
	::v-deep .el-date-editor {
		width: 100%;
	}
	.fileBox {
		display: flex;
		flex-direction: column;
	}
	.uploadFileBox {
		width: 80%;
		margin: 0 auto;
	}
	.upload-demo {
		display: flex;
		flex-direction: column;
		align-items: center;
	}
</style>
